package com.example.spider.util;

import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.shoulder.core.context.AppInfo;
import org.shoulder.core.exception.CommonErrorCodeEnum;
import org.shoulder.core.util.AssertUtils;
import org.shoulder.core.util.JsonUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.core.GenericTypeResolver;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.CronTrigger;

import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

/**
 * 定时全量刷新，适合少量数据无数据库存储
 */
@Slf4j
public class FileBasedMap<M extends Map<K, V>, K, V> implements Map<K, V>, DisposableBean {

    private static       Consumer<FileBasedMap<?, ?, ?>> registerConsumer;
    private static final Trigger                         periodOf10SecondTrigger = new CronTrigger("*/10 * * * * ?");
    private final        M                               map;
    private final        AtomicBoolean                   dirty                   = new AtomicBoolean(false);
    private final        Trigger                         syncToPersistenceStorageTrigger;

    private Class<M> mapClass;
    private Class<K> keyClass;
    private Class<V> valueClass;
    private File     storageFile;
    private String   name = "fileMap";

    private final ReentrantLock loadLock = new ReentrantLock();

    public <MM extends Map<KK, VV>, KK, VV> FileBasedMap<MM, KK, VV> create(MM m, File storageFile) {
        AssertUtils.notNull(registerConsumer, CommonErrorCodeEnum.ILLEGAL_STATUS, "context 未初始化，请使用 bean 注册形式使用.");
        FileBasedMap<MM, KK, VV> map = new FileBasedMap<>(m, storageFile);
        registerConsumer.accept(map);
        return map;
    }

    public static void setRegisterConsumer(Consumer<FileBasedMap<?, ?, ?>> c) {
        registerConsumer = c;
    }

    public FileBasedMap(M m, Class<K> keyClass, Class<V> valueClass, File storageFile) {
        this(m, storageFile, periodOf10SecondTrigger);
        this.keyClass = keyClass;
        this.valueClass = valueClass;
    }

    protected FileBasedMap(M m, File storageFile) {
        this(m, storageFile, periodOf10SecondTrigger);
    }

    public FileBasedMap(M m, File storageFile, Trigger syncToPersistenceStorageTrigger) {
        this.map = m;
        this.storageFile = storageFile;
        this.syncToPersistenceStorageTrigger = syncToPersistenceStorageTrigger;
    }

    @SuppressWarnings("unchecked")
    private void resolveClazz() {
        mapClass = (Class<M>) map.getClass();
        if (getClass() != FileBasedMap.class) {
            // 从子类上解析
            Class<?>[] classes = GenericTypeResolver.resolveTypeArguments(getClass(), FileBasedMap.class);
            assert classes != null;
            keyClass = (Class<K>) classes[1];
            valueClass = (Class<V>) classes[2];
        }
    }

    public void loadFromStorage() {
        loadLock.lock();
        try {
            if (storageFile.exists()) {
                if (mapClass == null) {
                    resolveClazz();
                }
                String str = FileUtil.readString(storageFile, AppInfo.charset());
                AssertUtils.notNull(keyClass, CommonErrorCodeEnum.CODING, name + "keyClass not set!");
                AssertUtils.notNull(valueClass, CommonErrorCodeEnum.ILLEGAL_PARAM, name + "keyClass not set!");
                Map<K, V> map = JsonUtils.parseObject(str, mapClass, keyClass, valueClass);
                log.info("load FileBasedMap({}, size={}) from storage: {}.", name, map.size(), storageFile);
                this.map.putAll(map);
            }
        } finally {
            loadLock.unlock();
        }
    }

    //@PreDestroy
    public void syncToPersistenceStorage() {
        if (dirty.get()) {
            synchronized (this) {
                if (!dirty.get()) {
                    return;
                }
                dirty.set(false);
            }
            FileUtil.writeString(JsonUtils.toJson(map, ObjectMapper::writerWithDefaultPrettyPrinter), storageFile, AppInfo.charset());
            log.info("sync FileBasedMap({}, size={}) to storage: {}.", name, map.size(), storageFile);
        }
    }

    public M getMap() {
        return map;
    }

    public File getStorageFile() {
        return storageFile;
    }

    public boolean isDirty() {
        return dirty.get();
    }

    public synchronized boolean changeStorageFile(File newFile) {
        if (MapUtils.isEmpty(map)) {
            storageFile = newFile;
            return true;
        }
        return false;
    }

    public void setKeyClass(Class<K> keyClass) {
        this.keyClass = keyClass;
    }

    public void setValueClass(Class<V> valueClass) {
        this.valueClass = valueClass;
    }
    // =======================================================

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return map.containsKey(value);
    }

    @Override
    public V get(Object key) {
        return map.get(key);
    }

    @Nullable
    @Override
    public V put(K key, V value) {
        V v = map.put(key, value);
        if (!Objects.equals(value, v)) {
            dirty.set(true);
        }
        return v;
    }

    @Override
    public V remove(Object key) {
        V v = map.remove(key);
        dirty.set(true);
        return v;
    }

    @Override
    public void putAll(@Nonnull Map<? extends K, ? extends V> m) {
        map.putAll(m);
        dirty.set(true);
    }

    @Override
    public void clear() {
        map.clear();
        dirty.set(true);
    }

    @Nonnull
    @Override
    public Set<K> keySet() {
        return map.keySet();
    }

    @Nonnull
    @Override
    public Collection<V> values() {
        return map.values();
    }

    @Nonnull
    @Override
    public Set<Entry<K, V>> entrySet() {
        return map.entrySet();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Trigger getSyncToPersistenceStorageTrigger() {
        return syncToPersistenceStorageTrigger;
    }

    @Override
    public void destroy() throws Exception {
        syncToPersistenceStorage();
    }
}
